package ext.tianma.loginAuth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.jfree.util.Log;

import wt.log4j.LogR;
import wt.util.WTProperties;

public class PropertiesUtil {
	
	private static final String CLASSNAME = PropertiesUtil.class.getName();
	private static Logger logger = LogR.getLogger(CLASSNAME);
	private static final String suffix = "properties";
	
	private Map<String, String> hmConfig = new HashMap<String, String>();
    private  long lastModifyTime = 0L;
    private File fileObj = null;
    private  String filepath = "";
    private static PropertiesUtil propertiesUtil = null;
    Properties pro = new Properties();
    public Properties getProperties(){
      return this.pro;
    }
	public PropertiesUtil(String configFilePath) {
        this.filepath = configFilePath;
        readConfig(false);
    }
	/**
	 * 通过key值和路径获取value
	 * @param    
	 * @param 
	 * @return      
	 * @throws IOException 
	 * @Exception
	 */
	public static String getValueByKey(String key,String path) throws IOException{
		if(checkFileName(path) && isFileExist(path)){
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8"));
			Properties props = new Properties();
			props.load(br);
			String value = props.getProperty(key);
			br.close();
			if(value != null && !value.isEmpty()){
				return value;
			}
		}
		return "";
	}
	
	/**
	 * 
	 * 方法名称: checkFileName
	 * 描       述 : 校验路径中的文件格式以及文件是否存在和正确
	 * 时       间 : 2016年6月26日 下午5:05:50     
	 * @param    
	 * @param 
	 * @return      
	 * @Exception
	 */
	public static boolean checkFileName(String path){
		logger.info(">>>>>>>>>>>"+CLASSNAME+"checkFileName()<<<<<<<<<<<<<");
		logger.info(">>>>>>>>>>>"+path+"<<<<<<<<<<<<<");
		if(!path.isEmpty() && path.length() > 0){
			int index = path.lastIndexOf(".");
			String suffix_ = path.substring(index + 1, path.length());
			if(suffix.equals(suffix_) && isFileExist(path)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 方法名称: isFileExist
	 * 描       述 : 根据路径判断文件是否存在   
	 * 时       间 : 2016年6月26日 下午6:15:53     
	 * @param    
	 * @param 
	 * @return      
	 * @Exception
	 */
	public static boolean isFileExist(String path){
		logger.info(">>>>>>>>>>>"+CLASSNAME+"isFileExist()<<<<<<<<<<<<<");
		logger.info(">>>>>>>>>>>"+path+"<<<<<<<<<<<<<");
		File file = new File(path);
		if(file.exists()){
			return true;
		} else {
			Log.error(">>>>>>>>>>>"+CLASSNAME+".properties File does not exist !");
			return false;
		}
	}
	
	public void readConfig(boolean createFile) {
        try {
        	WTProperties localPro = WTProperties.getLocalProperties();
            String wthome = localPro.getProperty("wt.home");
            fileObj = new File(wthome + File.separator + filepath);
            //文件不存在则自动创建文件
            if(createFile){
              File mkdirs = fileObj.getParentFile();
              if(!mkdirs.exists()){
              mkdirs.mkdirs();
            }
              if(!fileObj.exists()){
                fileObj.createNewFile();
          }
            }
            FileInputStream fis = new FileInputStream(fileObj/*wthome + File.separator + filepath*/);
            InputStreamReader isr=new InputStreamReader(fis,"utf-8");
            pro.load(isr);
            Enumeration enuPro = pro.propertyNames();
            hmConfig.clear();//读取前清除历史
            while (enuPro.hasMoreElements()) {
                String proName = (String) enuPro.nextElement();
                String proValue = (String) pro.getProperty(proName);
                try {
                  proName = new String(proName.getBytes("utf-8"),"utf-8");
                  proValue = new String(proValue.getBytes("utf-8"),"utf-8");
            } catch (UnsupportedEncodingException e) {
              logger.error(e.getMessage(), e);
            } 
                hmConfig.put(proName, proValue);
            }
            isr.close();
            fis.close();
            lastModifyTime = fileObj.lastModified();
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
	public String getValueByKey(String key) {
	      isUpdateFile();
	      //初始化已经处理转码，在继续处理会出乱码
	      String strValue = (String) hmConfig.get(key);
	        if (strValue == null || "".equals(strValue)) {
	            return "";
	        }
	        return strValue.trim();
	}
	private boolean isUpdateFile(){
	    long lastModify=fileObj.lastModified();
	    if(lastModify>lastModifyTime){
	      propertiesUtil.readConfig(false);
	      return true;
	    }
	    return false;
	  }
	public static List getPropertiesByKey(String filePath,String key) {
        List cadTypes = new ArrayList();
        try {
            PropertiesUtil pro = new PropertiesUtil(filePath);
            String strEPMTypes = pro.getValueByKey(key);
            String[] arr = strEPMTypes.split(",");
            for (int i = 0; i < arr.length; i++) {
                String s = arr[i];
                if (!cadTypes.contains(s)) {
                    cadTypes.add(s);
                }
            }
        } catch (Exception e) {

        }
        return cadTypes;
    }
}
